include('shared.lua')

include("sky_titans/shared/st_weapons.lua")

function ENT:Initialize()

    local weptable = st_weapons[self.Entity:GetModel()]
    self.cl_turn = weptable.turn or 0
    self.cl_recoil = weptable.recoil or {0,0}
    self.cl_reload = weptable.reload or 5
    self.cl_rate = weptable.rate or self.cl_reload
    
    self.cycle = 0
    self.fired = 0
    self.cl_repair = 1
    self.cl_driver = NULL

    self.destyaw = 0
    self.destpitch = 0
    self.aimyaw = 0
    self.aimpitch = 0
    self.CalcTime = CurTime()
    self.ManipTime = CurTime()

end

function ENT:Think()
    if(self.CalcTime<CurTime()) then
        self.cl_driver = self.Entity:GetNetworkedEntity("driver")
        self.cl_repair = self.Entity:GetNetworkedFloat("repair")
        
        self.destyaw = self.Entity:GetNetworkedFloat("yaw")
        self.destpitch = self.Entity:GetNetworkedFloat("pitch")
        local prevyaw = self.aimyaw
        local prevpitch = self.aimpitch
        self.aimyaw = math.ApproachAngle(self.aimyaw,self.destyaw,1.1*(self.cl_turn*(1+self.cl_repair)/2)/5)
        self.aimpitch = math.ApproachAngle(self.aimpitch,self.destpitch,1.1*(self.cl_turn*(1+self.cl_repair)/2)/10)
        
        //Handle recoil
        local lastfired = self.fired
        self.fired = self.Entity:GetNetworkedInt("fired")
        if(self.fired>lastfired) then
            self.cycle = 180
        end
        
        local prevcycle = self.cycle
        self.cycle = math.max(0,self.cycle-(0.1+(self.cycle/45))*(5/math.pow(self.cl_rate,0.5)))
        
        self.CalcTime = CurTime()+0.01
        
        if(self.ManipTime<CurTime()) then
        
            if(prevyaw==self.aimyaw) then /*comment*/ else
            self.Entity:ManipulateBoneAngles( 1, Angle(-self.aimyaw, 0 ,0)) end
            if(prevpitch==self.aimpitch) then /*comment*/ else
            self.Entity:ManipulateBoneAngles( 2, Angle(0,0, -self.aimpitch )) end
            if(prevcycle==self.cycle) then /*comment*/ else
            self.Entity:ManipulateBonePosition( 3, Vector(0,0,-math.min(1,math.sin(math.rad(self.cycle))*1.05)*self.cl_recoil[1]) ) end
            
            local dist = (LocalPlayer():GetShootPos() - self.Entity:GetPos()):Length()
            self.ManipTime = CurTime()+math.Clamp( 0.01 + math.floor(dist/1000)/100 ,0,1)
        end
        
    end

    if(self.cl_repair<1 and self.cl_driver==LocalPlayer()) then
        local pos = self.Entity:LocalToWorld(Vector(0,0,self.Entity:OBBCenter().z))
        repairhud_info[self.Entity:EntIndex()] = {vec = pos,val=self.cl_repair}
    end
end

function ENT:Draw()
	self:DrawModel()
end